#!/bin/bash
set -e


function help()
{
    echo -e "usage:"
    echo -e "./tf_upload.sh --upload_disk /dev/sdb --upload_file [file]"
    echo -e "./tf_upload.sh -d /dev/sdb -f [file]"

}


while [ -n "$1" ]
do
    case "$1" in
        --upload_disk|-d) 
            UPLOAD_DISK=$2
            shift
            ;;
        --upload_file|-f) 
            UPLOAD_FILE=$2
            shift
            ;;
        --help|-h) 
            help
            exit 1
            ;;
        *) echo "[-] Parameters of illegal !!!"
            help
            exit 1
            ;;
    esac
    shift
done


echo "UPLOAD_DISK=${UPLOAD_DISK}"
echo "UPLOAD_FILE=${UPLOAD_FILE}"



if [[ -z ${UPLOAD_DISK}  || -z ${UPLOAD_FILE} ]]
then
    echo -e "\e[31mParameters invalid !!!\e[0m"
    exit 1
fi
echo -e "\e[36mParameters OK !!!\e[0m"


sudo watch -n 10 killall -USR1 dd > /dev/null 2>&1 &

if [ "${UPLOAD_FILE##*.}" = "gz" ];
then
    gzip -dc ${UPLOAD_FILE} | sudo dd of=${UPLOAD_DISK} bs=8M
elif [ "${UPLOAD_FILE##*.}" = "img" ];
then 
    sudo dd if=${UPLOAD_FILE} of=${UPLOAD_DISK} bs=8M
fi

sudo killall watch
